﻿/*path: Assets\Scripts\Tools\FSM\TaskQueue.cs
 * 功能:用于执行任务队列
 * */

using System;
using System.Collections.Generic;

namespace CxExtension.Task
{
	/// <summary>
	/// 任务队列 用于处理异步,延迟
	/// </summary>
	public class TaskQueue<T> : ITaskItem where T : ITaskItem
	{
		private readonly Queue<T> mTasks = new Queue<T>();                      //

		public event Action<T> OnTaskComplete;//当任务处理完成时的回调

		public TaskQueue()
		{

		}
		public TaskQueue(params T[] tasks)
		{
			AddTasks(tasks);
		}

		/// <summary>
		/// 添加单个任务到队列中
		/// </summary>
		/// <param name="task"></param>
		public void AddTask(T task)
		{
			if(task == null) return;
			mTasks.Enqueue(task);
		}

		public void ForEach(Action<T> func)
		{
			if(func == null) return;
			foreach(var taskItem in mTasks)
			{
				func(taskItem);
			}
		}
		/// <summary>
		/// 添加任意个任务
		/// </summary>
		/// <param name="tasks"></param>
		public void AddTasks(params T[] tasks)
		{
			for(var i = 0; i < tasks.Length; i++)
			{
				var it = tasks[i];
				AddTask(it);
			}
		}

		public bool Start()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// 处理队列的任务
		/// </summary>
		/// <param name="dt"></param>
		/// <returns></returns>
		public bool Update(float dt)
		{
			if(mTasks.Count == 0)
			{
				return true;
			}

			var task = mTasks.Peek();
			if(task.Update(dt) == false) return false;

			if(OnTaskComplete != null) OnTaskComplete(task);
			mTasks.Dequeue();

			return mTasks.Count == 0;
		}

		public void End()
		{
			throw new NotImplementedException();
		}

		#region Implementation of IReset

		public void Reset()
		{
			
		}

		#endregion
	}
}